<template>
	<view class="content">
		<view class="uni-panel">
			<view class="uni-panel-item">
				<text class="uni-text-item">英文单词</text>
				<input class="uni-input" placeholder="请输入英文单词" v-model="wordValue"/>
			</view>
			<view class="uni-panel-item">
				<text class="uni-text-item">中文意思</text>
				<input class="uni-input" placeholder="请输入中文意思" v-model="wordZhValue"/>
			</view>
			<view class="uni-panel-item-right">
				<text class="uni-text-item" @click="btnBackClick">返回</text>
			</view>
			<view class="uni-panel-item">
				<button class="uni-btn-login" @click="btnLoginClick">添加到生词本</button>
				<button class="uni-btn-login" @click="btnCamera">智能扫一扫</button>
			</view>
		</view>
		<ksp-cropper class='panel-cropper' mode="free" :width="200" :height="140" :maxWidth="1024" :maxHeight="1024" :url="url" @cancel="oncancel" @ok="onok"></ksp-cropper>
	</view>
</template>

<script>
	import { editNewWord, aiOCR } from '@/api/api.js';
	import store from "../../store";
	export default {
		mounted() {
		        // #ifdef APP-PLUS
		        plus.screen.lockOrientation('landscape');
		        // #endif
		    },
		data() {
			return {
				userId: 0,
				newbook_id: 0,
				wordValue: '',
				wordZhValue: '',
				url: "",
			}
		},
		onLoad(options) {
			const userInfo = store.state.app.userInfo;
			if( userInfo){
				this.userId = userInfo.id;
			}
			let student = uni.getStorageSync('student_info');
			if( student){
				this.userId = student.id;
			}
			if( options.newbook_id){
				this.newbook_id = options.newbook_id;
			}
		},
		methods: {
			btnLoginClick(){
				if( this.wordValue == ''){
					uni.showToast({
					    title: '请输入英文单词',
						icon: 'error',
					    duration: 2000
					});
					return;
				}
				if( this.wordZhValue == ''){
					uni.showToast({
					    title: '请输入中文意思',
						icon: 'error',
					    duration: 2000
					});
					return;
				}

				let params = {word:this.wordValue, word_zh:this.wordZhValue, newbook_id:this.newbook_id, is_add:true};
				editNewWord(params).then(res => {
					//console.log(res)
					if( res.code == 0 && res.data){
						uni.showToast({
						    title: '添加生词本成功',
							icon: 'none',
						    duration: 2000
						});
					}else{
						uni.showToast({
						    title: res.msg,
							icon: 'none',
						    duration: 2000
						});
					}
				}).catch(err => {
					uni.showToast({
					    title: err,
						icon: 'none',
					    duration: 2000
					});
				});
			},
			btnBackClick(){
				uni.navigateBack()
			},
			btnCamera(){
				uni.chooseImage({
					count: 1, // 默认9, 设置图片的选择数量
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: (res) => {
						// 返回选定照片的本地文件路径列表 tempFilePaths
						console.log(res.tempFilePaths);
						this.url = res.tempFilePaths[0];
						//this.urlTobase64(res.tempFilePaths[0]);
					},
					fail: (err) => {
						// 处理错误情况
						console.error(err);
					}
				});
			},
			urlTobase64(url) {
				let that = this;
				// #ifdef H5
				uni.request({
					url: url,
					responseType: 'arraybuffer', //最关键的参数，设置返回的数据格式为arraybuffer
					success: (res) => {
						//把arraybuffer转成base64
						let base64 = uni.arrayBufferToBase64(res.data);
						//不加这串字符，在页面无法显示
						//base64 = 'data:image/jpeg;base64,' + base64;
						that.innerOCR(base64);
					},
					fail: (err) => {
						// 处理错误情况
						console.error(err);
					}
				});
				// #endif
				// #ifdef APP-PLUS
				plus.io.resolveLocalFileSystemURL(url, ( entry )=> {
					// 可通过entry对象操作test.html文件 
					entry.file((file)=>{
						let fileReader = new plus.io.FileReader();
						fileReader.onloadend = (evt)=> {
							//console.log(evt.target.result);
							const base64 = evt.target.result;//.substr(22);
							that.innerOCR(base64);
						}
						fileReader.readAsDataURL(file);
					} );
				},  ( e )=>{
					console.error( "Resolve file URL failed: " + e.message );
				} );
				// #endif
			},
			innerOCR(base64){
				uni.showLoading({ title: 'AI识别中...'	});
				let params = {user_id: this.userId, image: encodeURIComponent(base64)};
				aiOCR(params).then(res => {
					uni.hideLoading();
					if( res.code == 0 && res.data){
						this.handleWords(res.data);
					}else{
						uni.showToast({
						    title: res.msg,
							icon: 'none',
						    duration: 2000
						});
					}
				}).catch(err => {
					uni.hideLoading();
					uni.showToast({
					    title: err,
						icon: 'none',
					    duration: 2000
					});
				});
			},
			handleWords(data){
				let allWords = [];
				for( let item of data){
					let words = item.words.split(' ');
					for( let word of words){
						let lowerWord = word.toLowerCase();
						if (allWords.indexOf(lowerWord) < 0){
							allWords.push(lowerWord);
						}
					}
				}
				if( allWords.length <= 0){
					uni.showToast({
					    title: '未识别到有效单词',
						icon: 'none',
					    duration: 2000
					});
				}else{
					let toParams = {newbook_id: this.newbook_id, words: allWords.join(',')}
					let params = Object.keys(toParams)
						.map(key => `${key}=${encodeURIComponent(toParams[key])}`)
						.join('&');
					uni.navigateTo({
						url: '/pages/selectnew/index?' + params
					});
				}
			},
			onok(ev) {
				// console.log(ev.path)
				this.url = "";
				this.urlTobase64(ev.path);
			},
			oncancel() {
				// url设置为空，隐藏控件
				this.url = "";
			}
		}
	}
</script>

<style>
	page {
		height: 100%;
	}
	.content {
		width: 100%;
		height: 100%;
		background-image: url('../../static/img/registe.jpg');
		background-size: 100% 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.panel-cropper {
		position: fixed;
		width: 100%;
		height: 100%;
		top: 0;
		left: 0;
	}
	.uni-image {
		width: 50%;
	}
	.uni-image-logo {
		width: 20%;
	}
	.uni-panel {
		margin-left: 52%;
		margin-top: 14%;
		width: 45%;
		height: 50%;
		display: flex;
		flex-direction: column;
	}
	
	.uni-text-logo{
		color: slateblue;
		font-size: 7vmin;
		font-weight: bold;
		letter-spacing: 1rpx;
		font-family: "楷体";
	}
	
	.uni-panel-item {
		display: flex;
		flex-direction: row;
		align-items: center;
		margin-top: 4%;
		margin-left: 2%;
		font-size: 5vmin;
	}
	
	.uni-text-item{
		width: 25vmin;
		height: 100%;
		text-align: center;
	}
	
	.uni-panel-item-right {
		display: flex;
		flex-direction: row;
		margin-top: 4%;
		justify-content: flex-end;
		font-size: 5vmin;
	}
	.uni-input{
		font-size: 5vmin;
	}
	
	.uni-btn-login {
		background-color: slateblue;
		width: 40%;
		color: white;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 20rpx;
		margin-top: 2%;
	}
	
</style>
